package com.example.tangjiangxu.disklrucachedemo;

import android.content.Context;
import android.content.pm.PackageInfo;
import android.os.Environment;

import java.io.File;
import java.security.MessageDigest;

import libcore.io.DiskLruCache;

/**
 *
 */
public class DiskCacheUtil{
    private static final String TAG = "DiskCacheUtil";
    private static DiskLruCache mDiskUrlCache = null;
    //缓存文件夹下的子文件
    private static final String CACHE_DIR = "bitmap";
    //缓存最大数量
    private static final long MAX_CACHE_SIZE = 10 * 1024 * 1024;

    public static DiskLruCache getInstance(Context context) {
        if (mDiskUrlCache == null) {
            try {
                File cacheDir = getDiskCacheDir(context, CACHE_DIR);
                if (!cacheDir.exists()) {
                    cacheDir.mkdirs();
                }
                mDiskUrlCache = DiskLruCache.open(cacheDir, getAppVersion(context), 1, MAX_CACHE_SIZE);
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
        return mDiskUrlCache;
    }

    /**
     * 得到文件缓存目录
     * @return
     */
    private static File getDiskCacheDir(Context context, String uniqueName) {
        String cachePath;
        if (Environment.MEDIA_MOUNTED.equals(Environment.getExternalStorageState())
                || !Environment.isExternalStorageRemovable()) {
            // /sdcard/Android/data/<application>/cache
            cachePath = context.getExternalCacheDir().getPath();
        } else {
            // /data/data/<application pageage>/cache
            cachePath = context.getCacheDir().getPath();
        }
        return new File(cachePath + File.separator + uniqueName);
    }

    /**
     * 得到应用程序的版本号
     * 每当版本号改变，缓存路径下存储的所有数据都会被清理掉
     * @param context
     * @return
     */
    public static int getAppVersion(Context context) {
        try {
            PackageInfo info = context.getPackageManager().getPackageInfo(context.getPackageName(), 0);
            return info.versionCode;
        } catch (Exception e) {
            e.printStackTrace();
        }
        return 1;
    }

    /**
     * 得到MD5
     * @param key
     * @return
     */
    public static String getMD5(String key) {
        String cacheKey;
        try {
            final MessageDigest mDigest = MessageDigest.getInstance("MD5");
            mDigest.update(key.getBytes());
            StringBuilder sb = new StringBuilder();
            for (int i = 0; i < mDigest.digest().length; i++) {
                String hex = Integer.toHexString(0xFF & mDigest.digest()[i]);
                if (hex.length() == 1) {
                    sb.append('0');
                }
                sb.append(hex);
            }
            cacheKey = sb.toString();
        } catch (Exception e) {
            e.printStackTrace();
            cacheKey = String.valueOf(key.hashCode());
        }
        return cacheKey;
    }

}
